package com.ysy.logistics.exception;

import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.exception.NotPermissionException;
import cn.dev33.satoken.stp.StpUtil;
import com.ysy.common.resp.ResultData;
import com.ysy.common.resp.ReturnCodeEnum;
import com.ysy.logistics.entities.oam.OperationLog;
import com.ysy.logistics.myannotation.OperateLog;
import com.ysy.logistics.service.oam.OperationLogService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.Date;
import java.util.Map;
import java.util.Objects;

/**
 * @ClassDescription: 全局异常拦截器
 * @Author:姚斯羽
 * @Create:2025/3/12 13:58
 **/
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    @Resource
    private OperationLogService operationLogService;
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResultData<String> methodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e) {

        OperateLog operateLog = e.getParameter().getMethod().getAnnotation(OperateLog.class);
        if (Objects.nonNull(operateLog)){
            OperationLog operationLog = new OperationLog();
            String target =e.getBindingResult().getFieldError().getDefaultMessage() + "  \n"+ e.getTarget().toString();
            if (target.length()>256){
                target = target.substring(0,256);
            }
            Object loginId = null;
            try {
                loginId = StpUtil.getLoginId();
            } catch (Exception e1) {
                log.info("获取登录用户失败：{}", e1);
            }
            operationLog = operationLog.setLogType("异常日志")
                    .setUserId( Objects.nonNull(loginId)?loginId.toString():"")
                    .setLogName(operateLog.value())
                    .setClassName(e.getParameter().getMethod().getDeclaringClass().getName())
                    .setMethod(e.getParameter().getMethod().getName())
                    .setCreateTime(new Date())
                    .setSucceed("失败")
                    .setMessage(target);
            operationLogService.add(operationLog);
        }


        return ResultData.fail(ReturnCodeEnum.RC205.getCode() ,e.getBindingResult().getFieldError().getDefaultMessage());
    }
    /**
     * 默认全局异常处理。
     * @param e the e
     * @return ResultData
     */
    @ExceptionHandler(RuntimeException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public ResultData<String> exception(Exception e) {
        System.out.println("----come in GlobalExceptionHandler");
        log.error("全局异常信息exception:{}", e.getMessage(), e);
        return ResultData.fail(ReturnCodeEnum.RC500.getCode(),e.getMessage());
    }

    @ExceptionHandler(NotLoginException.class)
    public ResultData<ReturnCodeEnum> notLoginExceptionHandler(NotLoginException e) {
        return ResultData.fail(ReturnCodeEnum.NOT_LOGIN);
    }

    @ExceptionHandler(NotPermissionException.class)
    public ResultData<ReturnCodeEnum> notPermissionExceptionHandler(NotPermissionException e) {
        return ResultData.fail(ReturnCodeEnum.NOT_PERMISSION);
    }
}
